<style scoped>
  .sfz {
    background: #eaeff3;
    overflow: hidden;
  }
  .head{
    height:50px;
    /*border-bottom: 2px solid #dedde3;*/
    display: flex;
    justify-content: center;
    align-items:center;
    background: #ffffff;
    box-shadow:0 2px 4px rgba(0,0,0,0.1);
    position: relative;
    padding-top: 10px;
  }
  .head-left{
    position: absolute;
    width:40px;
    height:100%;
    left:0;
    top:0;
    color: #7f7a8e;
    text-align: center;
  }
  .head-left h1{
    margin-top: 22px;
  }
  .head-middle{
    font-size: 16px;
    color: #7f7a8e;
  }
  .head-right{
    position: absolute;
    right:14px;
    top:25px;
    color: #7f7a8e;
  }
  .content{
    width: 100%;
    display: flex;
    flex-direction: column;
    justify-content: space-around;
    color: #777287;
  }
  .content>label{
    width:90%;
    margin: 0 5%;
    background: #ffffff;
    border-radius: 16px;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    padding: 20px 0;
  }
  .content>div.sc>label{
    text-align: center;
  }
  #result1 p{
    margin-top: 6px;
  }
  .content .zhaopian img[src=""]{
    opacity: 0;
  }
  @media screen and (max-width: 320px) {
    .content .zhaopian img{
      width:120px;
      height:80px;
    }
    .sub{
      height:35px;
    }
  }
  @media screen and (max-width:375px) and (min-width:321px) {
    .content .zhaopian img{
      width:130px;
      height:88px;
    }
    .sub{
      height:39px;
    }
  }
  @media screen and (min-width: 376px){
    .content .zhaopian img{
      width:150px;
      height:100px;
    }
    .sub{
      height:45px;
    }
  }
  .content>div.sc>h1{
    margin-top: 10px;
  }
  .content>div.fan{
    /*margin-top: 40px;*/
  }
  .know{
    padding: 0 5%;
  }
  .sub{
    width:100%;
  }
  .sub a{
    background: #435cff;
    border:none;
    border-radius: 4px;
    display: flex;
    justify-content:center;
    align-items: center;
    margin: 0 10px;
    height:100%;
  }
  .sub a h3{
    color: #ffffff;
  }
  .mint-popup{
    width:96%;
  }
  .tanchu{
    width:100%;
    display: flex;
    flex-direction: column;
  }
  .tanchu ul li{
    text-align: center;
    border-bottom: 1px solid #eaeff3;
    padding: 8px 0;
  }
  .sfzsb{
    width:100%;
    position: absolute;
    bottom: 0;
    text-align: center;
    background: rgba(0,0,0,0.5);
    color: #ffffff;
    height:50px;
    line-height: 50px;
  }
</style>

<template>
  <div class="sfz" ref="sfz">
    <div class="head" style="position: fixed;top: 0;width: 100%">
      <div class="head-left" @click="goBack"><h1 class="iconfont icon-xiangzuo1"></h1></div>
      <div class="head-middle"><h3>宽策略证券开户</h3></div>
      <div class="head-right"  @click="contact"><h1 class="iconfont icon-kefu3"></h1></div>
    </div>
    <form id="form1" style="margin-top: 61px;">
      <canvas id="uploadImg" style="display:none"></canvas>
      <div class="content" ref="content">
        <template v-if="navigator.platform.indexOf('Linux') > -1">
          <label @click="checkInputType(1)" style="position: relative;">
            <div class="zheng sc" ref="first">
              <div id="result1" class="zhaopian">
                <img src="../assets/img/sfz3.png" alt="" data="imgtouch">
              </div>
              <p style="margin-top: 6px;text-align: center;">身份证正面照</p>
            </div>
            <p class="sfzsb" v-if="issfzzSuccess" z-index="9999">{{sfzzSuccess}}</p>
          </label>
          <label @click="checkInputType(2)" style="position: relative;">
            <div class="fan sc" ref="second">
              <div id="result2"  class="zhaopian">
                <img src="../assets/img/sfzbm3.png" alt="" data="imgtouch">
              </div>
              <p style="margin-top: 6px;text-align: center;">身份证反面照</p>
            </div>
            <p class="sfzsb" v-if="issfzfSuccess">{{sfzfSuccess}}</p>
          </label>
        </template>
        <template v-else>
        <label for="img-upload1" style="position: relative;">
          <div class="zheng sc" ref="first">
            <div id="result1" class="zhaopian">
              <img src="../assets/img/sfz3.png" alt="" data="imgtouch">
            </div>
            <p style="margin-top: 6px;text-align: center;">身份证正面照</p>
            <form ref="sfzzform">
              <input type="file" ref="sfzzinput" style="display: none;" id="img-upload1" accept="image/*" @change="uploadImg1($event)"/>
            </form>
          </div>
          <p class="sfzsb" v-if="issfzzSuccess">{{sfzzSuccess}}</p>
        </label>
        <label for="img-upload2" style="position: relative;">
          <div class="fan sc" ref="second">
            <div id="result2"  class="zhaopian">
              <img src="../assets/img/sfzbm3.png" alt="" data="imgtouch">
            </div>
            <p style="margin-top: 6px;text-align: center;">身份证反面照</p>
            <form ref="sfzfform">
              <input type="file" style="display: none;" id="img-upload2" accept="image/*" @change="uploadImg2($event)"/>
            </form>
          </div>
          <p class="sfzsb" v-if="issfzfSuccess">{{sfzfSuccess}}</p>
        </label>
        </template>
        <div class="know" ref="third">
          <p>上传须知</p>
          <ul>
            <li><p>1.完整拍摄本人有效期内身份证照片</p></li>
            <li><p>2.请确保身份证四边框清晰完整,文字清晰可辨</p></li>
            <li><p>3.照片无遮挡,避免反光</p></li>
            <li><p>4.开户全程仅需上传身份证,再无其他证件</p></li>
          </ul>
        </div>
        <div class="sub" @click="submit">
          <router-link to=""><h3>提交</h3></router-link>
        </div>
      </div>
    </form>
    <actionsheet theme="android" v-model="checkInputFile1" :menus="checkInputFileMenu" @on-click-menu="clickMenu1"></actionsheet>
    <actionsheet theme="android" v-model="checkInputFile2" :menus="checkInputFileMenu" @on-click-menu="clickMenu2"></actionsheet>
    <input type="file" capture="camera" data="fastClick" id="sfzzinput1" ref="sfzzinput1" accept="image/*" @change="uploadImg1($event)"/>
    <input type="file" data="fastClick" id="sfzzinput2" ref="sfzzinput2" accept="image/*" @change="uploadImg1($event)"/>
    <input type="file" capture="camera" data="fastClick" id="sfzfinput1" ref="sfzfinput1" accept="image/*" @change="uploadImg2($event)"/>
    <input type="file" data="fastClick" id="sfzfinput2" ref="sfzfinput2" accept="image/*" @change="uploadImg2($event)"/>
  </div>
</template>

<script>
  import axios from 'axios'
  import qs from 'qs'
  import host from '../config'
  import { Toast } from 'mint-ui'
  import {Indicator} from 'mint-ui'
  import { Actionsheet } from 'vux'

  export default {
    components: {
//      mtPopup: Popup
      Actionsheet
    },
    data () {
      return {
        imgList: null,
        popupVisible: false,
        img: {
          src: null
        },
        imgSrc: null,
        front: null,
        back: null,
//        姓名
        name: null,
        pic1:null,
        sfzz: null,
        sfzf: null,
//        年龄
        age: null,
        issfzzSuccess: false,
        issfzfSuccess: false,
        sfzzSuccess: null,
        sfzfSuccess: null,
        navigator: navigator,
        checkInputFile1: false,
        checkInputFile2: false,
        checkInputFileMenu: {
          menu1: '拍照',
          menu2: '从相册获取'
        }
      }
    },
    activated () {
      let that = this
      Indicator.open()
      axios({
        method: 'get',
        headers: {'Authorization': window.localStorage.getItem('token')},
        url: host.host + '/api/v1/trade/personInfo'
      }).then(function(data){
        Indicator.close()
        if(data.data.code === 6006) {
          that.$router.push('/login')
        }
        if(data.data.code == 6007){
          that.$refreshToken()
        }
        if(data.data.code ===200){
          let getData = data.data.data
          that.$store.state.openData = data.data.data
          if(that.$store.state.openData == undefined) {
            return
          }
          if(typeof that.$store.state.idFront == 'string') {
            document.getElementById('result1').innerHTML = '<img src="'+that.$store.state.idFront+'" alt="" width="120" height="80"  data="imgtouch"/>'
          }else{
            let img = '<img src="'+host.host+'/'+getData.sfzz+'" alt="" width="120" height="80" data="imgtouch"/>'
            document.getElementById('result1').innerHTML = img
          }
          if(typeof that.$store.state.idBack == 'string') {
            document.getElementById('result2').innerHTML = '<img src="'+that.$store.state.idBack+'" alt="" width="120" height="80"  data="imgtouch"/>'
          }else {
            document.getElementById('result2').innerHTML = '<img src="'+host.host+'/'+getData.sfzf+'" alt="" width="120" height="80" data="imgtouch"/>'
          }
        }
      }).catch((err) => {
        Indicator.close()
    })
    },
    mounted () {
      if(window.localStorage.getItem('token') === 'null' || !window.localStorage.getItem('token')) {
        this.$router.push('/login')
      }
      let w = window.innerWidth || document.documentElement.clientWidth || document.body.clientWidth
      let h = window.innerHeight || document.documentElement.clientHeight || document.body.clientHeight
      let nanaH = h
      let nanaH1 = h - 60
      this.$refs.content.style.height = nanaH1 + 'px'

    },
    methods: {
      checkInputType (par) {
        par === 1 ? this.checkInputFile1 = true : this.checkInputFile2 = true
      },
      clickMenu1 (menuKey, menuItem) {
        menuKey === 'menu1' ? this.sfzzCamera() : this.$refs.sfzzinput2.click()
      },
      clickMenu2 (menuKey, menuItem) {
        menuKey === 'menu1' ? this.sfzfCamera() : this.$refs.sfzfinput2.click()
      },
      toBase64 (img, height, width) {
        return new Promise((resolve, reject) => {
          var canvas = document.createElement("canvas");
          canvas.width = width;
          canvas.height = height;
          var ctx = canvas.getContext("2d");
          ctx.drawImage(img, 0, 0, img.width, img.height);
          var dataURL = canvas.toDataURL("image/png");
          resolve(dataURL)
        })
        // var canvas = document.createElement("canvas");
        // canvas.width = 1200;
        // canvas.height = 800;
        // var ctx = canvas.getContext("2d");
        // ctx.drawImage(img, 0, 0, img.width, img.height);

        // var dataURL = canvas.toDataURL("image/png");
        // return dataURL
      },
      sfzzCamera () {
        let cameraOptions = {
          quality: 90,
          destinationType: Camera.DestinationType.FILE_URI,
          sourceType: Camera.PictureSourceType.CAMERA,
          allowEdit: false,
          encodingType: Camera.EncodingType.PNG,
          saveToPhotoAlbum: false,
          correctOrientation: false
        }
        let base64Img = ''
        let height = 0
        let width = 0
        navigator.camera.getPicture((img) => {
          let that = this
          let imgTag = document.createElement('img')
          imgTag.src = img
          imgTag.onload = () => {
            height = (imgTag.height > imgTag.width) ? 1200 : 800
            width = (imgTag.height > imgTag.width) ? 800 : 1200
            imgTag.height = height
            imgTag.width = width
            this.toBase64(imgTag, height, width).then((res) => {
              base64Img = res
              var arr=base64Img.split(',')
              that.sfzz = base64Img
              that.$store.state.idFront = base64Img
              document.getElementById('result1').innerHTML = '<img src="'+base64Img+'" alt="" width="120" height="80"  data="imgtouch"/>'
              axios({
                method: 'post',
                headers: {'Authorization': window.localStorage.getItem('token'),'Content-Type': 'raw'},
                url: host.host + '/api/trade/idCardOCR',
                data: JSON.stringify({
                  id_card_side: 'front',
                  detect_direction: true,
                  image: arr[1]
                })
              }).then(function (data) {
                Indicator.close()
                if(data.data.code === 6006) {
                  that.$router.push('/login')
                }
                if(data.data.code === 6007){
                  that.$refreshToken()
                }
                if(data.data.code === 200){
                  that.front = data.data.data
                  if(that.front.words_result.住址){
                    that.issfzzSuccess = true
                    that.sfzzSuccess = '身份证正面识别成功'
                  }else{
                    that.issfzzSuccess = true
                    that.sfzzSuccess = '身份证正面识别失败'
                  }
                  that.$store.state.idmessage = data.data.data
                  let sfz = data.data.data.words_result.公民身份号码.words
                  that.age = (new Date()).getFullYear() - parseInt(sfz.substring(6,10))
                  that.name = that.front.words_result.姓名.words
                }
              }).catch(function (err) {
                Indicator.close()
              })
            })
          }
          that.issfzzSuccess = false
          // var arr=img.split(',')
          Indicator.open()
        }, () => {

        }, cameraOptions);
      },
      sfzfCamera () {
        let cameraOptions = {
          quality: 90,
          destinationType: Camera.DestinationType.FILE_URI,
          sourceType: Camera.PictureSourceType.CAMERA,
          allowEdit: false,
          encodingType: Camera.EncodingType.PNG,
          saveToPhotoAlbum: false,
          correctOrientation: false
        }
        let base64Img = ''
        let height = 0
        let width = 0
        navigator.camera.getPicture((img) => {
          let that = this
          let imgTag = document.createElement('img')
          imgTag.src = img
          imgTag.onload = () => {
            height = (imgTag.height > imgTag.width) ? 1200 : 800
            width = (imgTag.height > imgTag.width) ? 800 : 1200
            imgTag.height = height
            imgTag.width = width
            this.toBase64(imgTag, height, width).then((res) => {
              base64Img = res
              var arr=base64Img.split(',')
              that.sfzf = base64Img
              that.$store.state.idBack = base64Img
              document.getElementById('result2').innerHTML = '<img src="'+base64Img+'" alt="" width="120" height="80" data="imgtouch"/>'
              axios({
                method: 'post',
                headers: {'Authorization': window.localStorage.getItem('token'),'Content-Type': 'raw'},
                url: host.host + '/api/trade/idCardOCR',
                data: JSON.stringify({
                  id_card_side: 'back',
                  detect_direction: true,
                  image: arr[1]
                })
              }).then(function (data) {
                Indicator.close()
                if(data.data.code == 6006){
                  that.$refreshToken()
                }

                if(data.data.code === 200){
                  that.back = data.data.data
                  if(that.back.words_result.失效日期){
                    that.issfzfSuccess = true
                    that.sfzfSuccess = '身份证反面识别成功'
                  }else{
                    that.issfzfSuccess = true
                    that.sfzfSuccess = '身份证反面识别失败'
                  }
                  that.$store.state.idmessageBack = data.data.data
                }
              }).catch(function (err) {
                Indicator.close()
              })
            })
          }
          that.issfzfSuccess = false
          Indicator.open()
        }, () => {

        }, cameraOptions);
      },
      uploadImg1 (e) {
        var files = e.target.files || e.dataTransfer.files
        var file = files[0];
        let size = file.size
        let scale
        if(size > 1048576) {
          scale = Math.sqrt(size/1048576)
        } else {
          scale = 1
        }
        var reader = new FileReader();
        reader.readAsDataURL(file);
        let that = this
        reader.onload = function(e) {
            Indicator.open()
            var canvas = document.getElementById("uploadImg");
            var cxt = canvas.getContext('2d');
            var img = new Image();
            img.src = this.result;
            that.$store.state.idFront = this.result
            that.sfzz = this.result
            img.onload = function() {
              canvas.width = img.width/scale;
              canvas.height = img.height/scale;
              cxt.drawImage(img, 0, 0, img.width/scale,img.height/scale);
              let _that = that
              axios({
                method: 'post',
                headers: {'Authorization': window.localStorage.getItem('token'),'Content-Type': 'raw'},
                url: host.host + '/api/trade/idCardOCR',
                data: JSON.stringify({
                  id_card_side: 'front',
                  detect_direction: true,
                  image: canvas.toDataURL("image/jpeg", 0.9).split(',')[1]
                })
              }).then(function (data) {
                Indicator.close()
                if(data.data.code === 6006) {
                  that.$router.push('/login')
                }
                if(data.data.code === 6007){
                  that.$refreshToken()
                }
                if(data.data.code === 200){
                  let getImage = canvas.toDataURL("image/jpeg", 0.9)
                  document.getElementById('result1').innerHTML = '<img src="'+getImage+'" alt="" width="120" height="80"  data="imgtouch"/>'
                  _that.front = data.data.data

                  if(_that.front.words_result.住址){
                    _that.issfzzSuccess = true
                    _that.sfzzSuccess = '身份证正面识别成功'
                  }else{
                    _that.issfzzSuccess = true
                    _that.sfzzSuccess = '身份证正面识别失败'
                  }
                  _that.$store.state.idmessage = data.data.data
                  _that.name = that.front.words_result.姓名.words
                }
              }).catch(function (err) {
                Indicator.close()
              })
            }
        }
      },

      uploadImg2 (e) {
        var files = e.target.files || e.dataTransfer.files
        var file = files[0];
        let size = file.size
        let scale
        if(size > 1048576) {
          scale = Math.sqrt(size/1048576)
        } else {
          scale = 1
        }
        var reader = new FileReader();
        reader.readAsDataURL(file);
        let that = this
        reader.onload = function(e) {
          Indicator.open()
          var canvas = document.getElementById("uploadImg");
          var cxt = canvas.getContext('2d');
          var img = new Image();
          img.src = this.result;
          that.$store.state.idBack = this.result
          img.onload = function() {
            canvas.width = img.width/scale;
            canvas.height = img.height/scale;
            cxt.drawImage(img, 0, 0, img.width/scale,img.height/scale);
            let _that = that
            axios({
              method: 'post',
              headers: {'Authorization': window.localStorage.getItem('token'),'Content-Type': 'raw'},
              url: host.host + '/api/trade/idCardOCR',
              data: JSON.stringify({
                id_card_side: 'back',
                detect_direction: true,
                image: canvas.toDataURL("image/jpeg", 0.9).split(',')[1]
              })
            }).then(function (data) {
              Indicator.close()
              if(data.data.code === 6006) {
                that.$router.push('/login')
              }
              if(data.data.code === 6007){
                that.$refreshToken()
              }
              if(data.data.code === 200){
                let getImage = canvas.toDataURL("image/jpeg", 0.9)
                document.getElementById('result2').innerHTML = '<img src="'+getImage+'" alt="" width="120" height="80"  data="imgtouch"/>'
                _that.front = data.data.data
                if(_that.front.words_result.失效日期){
                  _that.issfzfSuccess = true
                  _that.sfzfSuccess = '身份证反面识别成功'
                }else{
                  _that.issfzfSuccess = true
                  _that.sfzfSuccess = '身份证反面识别失败'
                }
                that.$store.state.idmessageBack = data.data.data
                _that.name = that.front.words_result.姓名.words
              }
            }).catch(function (err) {
              Indicator.close()
            })
          }
        }
      },
//      createImage2 (file) {
//        var pic = {}
//        var reader = new FileReader()
//        let that = this
//        reader.onloadend = function (e) {
//          that.sfzf = this.result
//          var arr=this.result.split(',')
//          that.$store.state.idBack = this.result
//          document.getElementById('result2').innerHTML = '<img src="'+this.result+'" alt="" width="120" height="80" data="imgtouch"/>'
//          Indicator.open()
//          axios({
//            method: 'post',
//            headers: {'Authorization': window.localStorage.getItem('token'),'Content-Type': 'raw'},
//            url: host.host + '/api/trade/idCardOCR',
//            timeout: 10000,
//            data: JSON.stringify({
//              id_card_side: 'back',
//              detect_direction: true,
//              image: arr[1]
//            })
//          }).then(function (data) {
//            Indicator.close()
//            if(data.data.code == 6006){
//              that.$refreshToken()
//            }
//            if(data.data.code === 200){
//              that.back = data.data.data
//              if(that.back.words_result.失效日期){
//                that.issfzfSuccess = true
//                that.sfzfSuccess = '身份证反面识别成功'
//              }else{
//                that.issfzfSuccess = true
//                that.sfzfSuccess = '身份证反面识别失败'
//              }
//              that.$store.state.idmessageBack = data.data.data
//            }
//          }).catch(function (err) {
//            Indicator.close()
//          })
//        }
//        reader.readAsDataURL(file)
//      },
      submit () {
        // if(this.$store.state.openData.sfzz && this.$store.state.openData.sfzf && this.front === null && this.back === null){
        //   this.$router.push('./open3')
        // }else if(this.$store.state.openData.sfzz && this.$store.state.openData.sfzf && this.front === null && this.back !== null ){
        //   if(this.back.words_result == undefined){
        //     Toast({
        //       message: '请上传身份证反面照片',
        //       duration: 1000
        //     })
        //     return
        //   }
        //   this.$router.push('./open3')
        // } else if (this.$store.state.openData.sfzz && this.$store.state.openData.sfzf && this.front !== null && this.back === null){
        //   if(this.front.words_result == undefined) {
        //     Toast({
        //       message: '请上传身份证正面照片',
        //       duration: 1000
        //     })
        //     return
        //   }
        //   if(this.age<21){
        //     Toast({
        //       message: '暂不支持21周岁以下开户',
        //       duration: 1000
        //     })
        //     return
        //   }
        //   this.$router.push('./open3')
        // }else {
        //   let that = this
        //   if(this.sfzz === this.sfzf){
        //     Toast({
        //       message: '请勿上传相同图片',
        //       duration: 1000
        //     })
        //     return
        //   }
        //   if(this.front === null || this.front.words_result == undefined ){
        //     Toast({
        //       message: '请上传身份证正面照片',
        //       duration: 1000
        //     })
        //     return
        //   }
        //   if( this.back === null || this.back.words_result == undefined){
        //     Toast({
        //       message: '请上传身份证反面照片',
        //       duration: 1000
        //     })
        //     return false
        //   }
        //   if(this.age<21){
        //     Toast({
        //       message: '暂不支持21周岁以下开户',
        //       duration: 1000
        //     })
        //     return
        //   }
        //   this.$router.push('./open3')
        // }
        if(this.$store.state.idmessage !== null && this.$store.state.idmessageBack !== null) {
          this.$router.push('./open3')
        }else if(this.$store.state.openData){
          this.$router.push('./open3')
        }else if(!this.$store.state.openData.sfzz && !this.$store.state.openData.sfzf && this.$store.state.idmessage === null || this.$store.state.idmessageBack === null){
          Toast({
            message: '请上传照片',
            duration: 1500
          })
        }else{
          this.$router.push('./open3')
        }
      },
      goBack () {
        this.$router.push('./index')
      },
      contact () {
        window.location.href = 'tel:400-900-6687'
      }
    }
  }
</script>
